package cn.hpclub.server.controller.admin;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.DeviceVersion;

public class DeviceversionController extends BaseAdminController<DeviceVersion>{
    private static Logger       log        = LoggerFactory.getLogger(DeviceversionController.class);
    private static final String APP_TYPE   = "app_type";
    private static final String START_DATE = "start_date";
    private static final String END_DATE   = "end_date";

    /**
     * @Title: 获取角色列表
     */
    public void list(){
        ConcurrentHashMap<String, String> searchInfo = getSearchParams();
        query(searchInfo);
    }

    /**
     * @Title: create
     * @Description:发布版本 void
     */
    public void create(){
        DeviceVersion version = new DeviceVersion();
        version.put("id", -1);
        version.put("type", 2);
        version.put("ispublic", 0);
        version.put("isForceUpdate", 0);
        setAttr("version", version);
        render("/admin/deviceversion_input.tpl");
    }

    /**
     * @Title: edit
     * @Description:修改版本 void
     */
    public void edit(){
        int id = getParaToInt("id");
        DeviceVersion version = DeviceVersion.dao.findById(id);
        setAttr("version", version);
        render("/admin/deviceversion_input.tpl");
    }

    /**
     * @Title:save
     * @Description:保存版本数据 void
     */
    @Before(Tx.class)
    public void save(){
        DeviceVersion version = getVersionDataFromParams();
        int id = getParaToInt("version.id");
        if(id == -1){
            /* 新增 */
            version.save();
            log.info("add id=" + version.getInt("id"));
        } else{
            /* 修改 */
            version.set("id", id);
            version.update();
        }
        redirect("/deviceversion/list");
    }

    /**
     * @Title: getVersionDataFromParams
     * @Description:从Request请求中获取版本数据
     * @return DeviceVersion 版本数据
     */

    private DeviceVersion getVersionDataFromParams(){
        DeviceVersion version = new DeviceVersion();
        version.set("type", getPara("version.type")).set("appName", getPara("version.appName"))
                .set("version", getPara("version.version")).set("downloadPath", getPara("version.downloadPath"))
                .set("fileName", getPara("version.fileName")).set("fileSize", getPara("version.fileSize"))
                .set("md5", getPara("version.md5")).set("ispublic", getPara("version.ispublic"))
                .set("isForceUpdate", getPara("version.isForceUpdate"))
                .set("description", getPara("version.description")).set("addTime", new Date())
                .set("appid", Constant.APPID).set("sysflage", 0);
        return version;
    }

    /**
     * @Title: getSearchParams
     * @Description:获取查询参数
     * @return ConcurrentHashMap<String,String>
     */
    private ConcurrentHashMap<String, String> getSearchParams(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        log.debug("searchInfo=" + searchInfo);
        if(StrKit.isBlank(searchInfo.get(APP_TYPE))){
            searchInfo.put(APP_TYPE, "0");
        }
        if(StrKit.isBlank(searchInfo.get(START_DATE))){
            searchInfo.put(START_DATE, "");
        }
        if(StrKit.isBlank(searchInfo.get(END_DATE))){
            searchInfo.put(END_DATE, "");
        }
        log.debug("searchInfo=" + searchInfo);
        return searchInfo;
    }

    /**
     * @Title: query
     * @Description:支持查询操作
     * @param searchInfo
     *            查询参数 void
     */
    private void query(ConcurrentHashMap<String, String> searchInfo){
        findByPageDeviceVersion(searchInfo);
        setAttrs(searchInfo);
        render("/admin/deviceversion_list.tpl");
    }

    /**
     * @Title: findByPageDeviceVersion
     * @Description:分页查询，查询结果写入Response中
     * @param searchInfo
     *            查询参数 void
     */
    private void findByPageDeviceVersion(ConcurrentHashMap<String, String> searchInfo){
        String select = "SELECT id, (CASE type WHEN 1 THEN 'IOS版本' WHEN 2 THEN 'Android版本' END) AS type, appName, version, fileName, fileSize, ispublic, isForceUpdate";
        int pageNumber = getParaToInt(PAGE_NUMBER, 1);
        String sqlExceptSelect = getSelectSql(searchInfo);
        log.debug("sqlExceptSelect=" + sqlExceptSelect);
        Page<DeviceVersion> pager = DeviceVersion.dao.paginate(pageNumber, getParaToInt(PAGE_SIZE, 10), select,
                                                               sqlExceptSelect);
        /* 删除最后一页所有数据后，显示最后一页前一页 */
        if(pager.getPageNumber() > 1 && pager.getList().size() == 0){
            pager = DeviceVersion.dao.paginate(pageNumber - 1, getParaToInt(PAGE_SIZE, 10), select, sqlExceptSelect);
        }

        setAttr(PAGER, pager);
    }

    /**
     * @Title: getSelectSql
     * @Description:根据查询条件查询SQL语句
     * @param searchInfo
     *            查询参数
     * @return String SQL语句
     */
    private String getSelectSql(ConcurrentHashMap<String, String> searchInfo){
        String sqlExceptSelect = "FROM device_version WHERE appid=" + Constant.APPID + " ";
        String appType = searchInfo.get(APP_TYPE);
        if(!StrKit.isBlank(appType) && !appType.equals("0")){
            sqlExceptSelect += " and type=" + appType;
        }
        String dateFormate = "%Y-%m-%d";
        String startDate = searchInfo.get(START_DATE);
        if(!StrKit.isBlank(startDate)){
            sqlExceptSelect += String.format(" and date_format(addTime, '%s')>=date_format('%s','%s')", dateFormate,
                                             startDate, dateFormate);
        }
        String endDate = searchInfo.get(END_DATE);
        if(!StrKit.isBlank(endDate)){
            sqlExceptSelect += String.format(" and date_format(addTime, '%s')<=date_format('%s','%s')", dateFormate,
                                             endDate, dateFormate);
        }

        sqlExceptSelect += " ORDER BY ispublic DESC, version DESC ";
        return sqlExceptSelect;
    }

    // 删除
    @Before(Tx.class)
    public void delete(){
        deleteById(Constant.Table.DEVICE_VERSION);
    }
}
